const app = getApp()

Page({
  data: {
    articles: [],
    categories: [],
    selectedCategory: 0,
    page: 1,
    perPage: 10,
    hasMore: true,
    loading: false,
    refreshing: false
  },

  onLoad() {
    this.loadCategories()
    this.loadArticles()
  },

  onShow() {
    // 页面显示时刷新数据
    this.refreshData()
  },

  onPullDownRefresh() {
    this.refreshData()
  },

  onReachBottom() {
    if (this.data.hasMore && !this.data.loading) {
      this.loadMore()
    }
  },

  // 加载分类
  loadCategories() {
    wx.request({
      url: `${app.globalData.baseUrl}/articles/categories`,
      method: 'GET',
      success: (res) => {
        if (res.data.success) {
          this.setData({
            categories: res.data.data
          })
        }
      },
      fail: (err) => {
        console.error('加载分类失败:', err)
        wx.showToast({
          title: '加载分类失败',
          icon: 'none'
        })
      }
    })
  },

  // 加载文章列表
  loadArticles(refresh = false) {
    if (this.data.loading) return

    this.setData({ loading: true })

    const params = {
      page: refresh ? 1 : this.data.page,
      per_page: this.data.perPage
    }

    if (this.data.selectedCategory > 0) {
      params.category_id = this.data.selectedCategory
    }

    wx.request({
      url: `${app.globalData.baseUrl}/articles/`,
      method: 'GET',
      data: params,
      header: app.globalData.token ? {
        'Authorization': `Bearer ${app.globalData.token}`
      } : {},
      success: (res) => {
        if (res.data.success) {
          const newArticles = res.data.data.items
          const total = res.data.data.total
          const currentPage = res.data.data.page
          const hasMore = currentPage * this.data.perPage < total

          this.setData({
            articles: refresh ? newArticles : [...this.data.articles, ...newArticles],
            page: currentPage + 1,
            hasMore: hasMore,
            loading: false,
            refreshing: false
          })

          if (refresh) {
            wx.stopPullDownRefresh()
          }
        } else {
          wx.showToast({
            title: res.data.message || '加载失败',
            icon: 'none'
          })
        }
      },
      fail: (err) => {
        console.error('加载文章失败:', err)
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
        this.setData({ 
          loading: false, 
          refreshing: false 
        })
        if (refresh) {
          wx.stopPullDownRefresh()
        }
      }
    })
  },

  // 选择分类
  selectCategory(e) {
    const categoryId = parseInt(e.currentTarget.dataset.id)
    this.setData({
      selectedCategory: categoryId,
      page: 1,
      hasMore: true,
      articles: []
    })
    this.loadArticles(true)
  },

  // 加载更多
  loadMore() {
    this.loadArticles()
  },

  // 刷新数据
  refreshData() {
    this.setData({
      refreshing: true,
      page: 1,
      hasMore: true
    })
    this.loadArticles(true)
  },

  // 跳转到文章详情
  goToArticle(e) {
    const articleId = e.currentTarget.dataset.id
    wx.navigateTo({
      url: `/pages/article-detail/article-detail?id=${articleId}`
    })
  }
}) 